package cn.tedu.mall.search.test;

import java.util.Arrays;

public class MargeSort {
    public static void main(String[] args) {
        int[] a = {21, 31, 23, 8, 12, 3, 81, 20, 939, 19, 23, 91, 9, 2};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }

    private static void sort(int[] a) {
        int[] temp = new int[a.length];
        sort(a, 0, a.length - 1, temp);
    }

    private static void sort(int[] a, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }
        int mid = (left + right / 2); //中间下标
        sort(a, left, mid, temp); //对左侧数据排序
        sort(a, mid + 1, right, temp); //对右侧数据排序
        marge(a, left, mid, right, temp);
    }

    private static void marge(int[] a, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int k = left;
        while (i <= mid && j <= right) {
            temp[k] = a[j];
        }
    }
}
